package com.dyz.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;


import java.time.LocalDateTime;
import java.util.Date;

@Component
public class AutoFillHandler implements MetaObjectHandler {
    /**
     * 填充新增数据
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        Long userId=getCurrentUserId();
        this.strictInsertFill(metaObject,"created", LocalDateTime.class,LocalDateTime.now());
        this.strictInsertFill(metaObject,"lastUpdateTime", LocalDateTime.class,LocalDateTime.now());
        this.strictInsertFill(metaObject,"createBy", Long.class,userId);
    }

    /**
     * 填充修改数据
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        Long userId=getCurrentUserId();
        this.strictUpdateFill(metaObject,"lastUpdateTime", LocalDateTime.class,LocalDateTime.now());
        this.strictUpdateFill(metaObject,"modifyBy", Long.class,userId);
    }

    private Long getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(authentication!=null){
            return Long.parseLong(authentication.getPrincipal().toString());
        }
        return null;
    }
}
